package com.s2.link;

public class LRULinkedList extends LinkedList {
	
	private static final int DEFAULT_LENGTH = 10;
	
	private final int length;
	
	private int used = 0;

	public LRULinkedList() {
		this(DEFAULT_LENGTH);
	}
	
	public LRULinkedList(int length) {
		this.length = length;
	}
	
	protected boolean isFull () {
		return this.used == this.length;
	}
	
	@Override
	public void add(Integer data) {
		/**
		 * 如果不存在 
		 *   队列未满则插入 tail
		 *   队列已满移除head并从插入 tail		 
		 * 如果存在 则从中取出并从插入 tail
		 */	
		Object removeNode = this.remove(data);
		if (removeNode == null && this.isFull()) {
			this.removeFirst();		
		}
		this.addLast(data);
	}
	
	@Override
	public Object remove(Object obj) {
		Object removeObject = super.remove(obj);
		if (removeObject != null) {
			this.used--;
		}		
		return removeObject;
	}
	
	@Override
	public Object removeFirst() {
		Object removeObject = super.removeFirst();
		if (removeObject != null) {
			this.used--;
		}		
		return removeObject;
	}
	
	@Override
	public void addLast(Integer data) {
		super.addLast(data);
		used++;
	}
}
